//
//  PrivateIMNet.m
//  SportSocial
//
//  Created by yull on 15/1/4.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "PrivateIMNet.h"
#import "IM_Service+Write.h"
#import "PrivateMsgDao.h"
#import <AFHTTPRequestOperationManager.h>
#import "IMNet.h"
#import "CurrentChat.h"
#import "FunctionMethod.h"
#import "ChatInfoDao.h"

@implementation PrivateIMNet

+ (instancetype)shareInstance
{
    static PrivateIMNet *privateNet = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        privateNet = [[PrivateIMNet alloc] init];
    });
    return privateNet;
}

- (instancetype)init
{
    if (self = [super init]) {
        self.msgArray = [NSMutableArray array];
        
        NSArray *pidArray = @[[NSNumber numberWithInteger:Friend_SendMsg_Receive_PID],[NSNumber numberWithInteger:Friend_RecMsg_Receive_PID]];
        [self.arrayPid addObjectsFromArray:pidArray];
        
        self.timer = [NSTimer scheduledTimerWithTimeInterval:60.0f
                                                      target:self
                                                    selector:@selector(handleTimer:)
                                                    userInfo:nil
                                                     repeats:YES];
    }
    return self;
}

#pragma mark - 发送消息
//发送文本
- (void)sendPrivateTextMsg:(PrivateChatMsg *)chatMsg isResend:(BOOL)resend
{
    BOOL ret = YES;
    if (!resend) {
        ret = [[PrivateMsgDao shareInstance] insertPrivateChatMsg:chatMsg];
    }
    
    ChatInfo *chatInfo = [ChatInfo chatInfoWithPrivateMsg:chatMsg];
    ret &= [[ChatInfoDao shareInstance] addOrUpdateChatInfo:chatInfo];
    
    if (ret) {
        if (![FunctionMethod networkAvailable] || ![IM_Service instance].isConnected) {
            chatMsg.sendStatus = ChatMsgSendStatusFail;
        }else {
            [self.msgArray addObject:chatMsg];
            
            ChatMsgBody_Builder *builder = [[ChatMsgBody builder] setMsgNum:chatMsg.dbId];
            builder = [builder setSendId:[CurrentUser shareInstance].userId];
            builder = [builder setSenderName:[CurrentUser shareInstance].name];
            builder = [builder setMsg:chatMsg.content];
            builder = [builder setCreateTime:[[NSDate date] timeIntervalSince1970]];
            builder = [builder setMsgType:ChatMsgTypeText];
            builder = [builder setCreateTime:chatMsg.createTime];
            
            PrivateChatMsgCG *sendPrivateChatMsg = [[[[PrivateChatMsgCG builder] setChatMsg:[builder build]] setRecieveId:chatMsg.receiveId] build];
            
            NSData *sendData = [sendPrivateChatMsg data];
            
            [[IM_Service instance] sendData:sendData protocolId:Friend_SendMsg_Send_PID];
        }
        
        if (resend) {
            [self updateSendStatusWithDbId:chatMsg.dbId status:chatMsg.sendStatus];
        }else {
            [self sendInsertChatMsgNotificationWithMsgArray:[NSArray arrayWithObject:chatMsg]];
        }
    }
}

//发送语音
- (void)sendPrivateAudioMsg:(PrivateChatMsg *)chatMsg audioData:(NSData *)audioData isResend:(BOOL)resend
{
    BOOL ret = NO;
    if (!resend) {
        ret = [[PrivateMsgDao shareInstance] insertPrivateChatMsg:chatMsg];
    }else {
        ret = [[PrivateMsgDao shareInstance] updateChatMsg:chatMsg];
    }
    
    ChatInfo *chatInfo = [ChatInfo chatInfoWithPrivateMsg:chatMsg];
    ret &= [[ChatInfoDao shareInstance] addOrUpdateChatInfo:chatInfo];
    
    if (ret) {
        [IMNet sendPrivateAudioWithData:audioData receiveId:chatMsg.receiveId successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSString *url = [responseObject objectForKey:@"data"];
            if ([[PrivateMsgDao shareInstance] updateMsgId:chatMsg.dbId preview:url original:@""]) {
                NSLog(@"更新语音地址成功!");
            }else {
                NSLog(@"更新语音地址失败!");
            }
            [self updateSendStatusWithDbId:chatMsg.dbId status:ChatMsgSendStatusSuccess];
        } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
            [self updateSendStatusWithDbId:chatMsg.dbId status:ChatMsgSendStatusFail];
        }];
        
        if (resend) {
            [self updateSendStatusWithDbId:chatMsg.dbId status:chatMsg.sendStatus];
        }else {
            [self sendInsertChatMsgNotificationWithMsgArray:[NSArray arrayWithObject:chatMsg]];
        }
    }
}

- (void)sendPrivatePicMsg:(PrivateChatMsg *)chatMsg imageData:(NSData *)imageData isResend:(BOOL)resend
{
    BOOL ret = NO;
    if (!resend) {
        ret = [[PrivateMsgDao shareInstance] insertPrivateChatMsg:chatMsg];
    }else {
        ret = [[PrivateMsgDao shareInstance] updateChatMsg:chatMsg];
    }
    
    ChatInfo *chatInfo = [ChatInfo chatInfoWithPrivateMsg:chatMsg];
    ret &= [[ChatInfoDao shareInstance] addOrUpdateChatInfo:chatInfo];
    
    if (ret) {
        AFHTTPRequestOperation *operation = [IMNet sendPrivatePicWithData:imageData receiveId:chatMsg.receiveId successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"上传私聊图片:%@",responseObject);
            
            NSDictionary *dataDict = [responseObject objectForKey:@"data"];
            NSString *original_img = [dataDict objectForKey:@"original_img"];
            NSString *preview_img = [dataDict objectForKey:@"preview_img"];
            chatMsg.url = preview_img;
            chatMsg.bigImageUrl = original_img;
            
            if ([[PrivateMsgDao shareInstance] updateMsgId:chatMsg.dbId preview:preview_img original:original_img]) {
                NSLog(@"更新图片地址成功!");
            }else {
                NSLog(@"更新图片地址失败!");
            }
            [self updateSendStatusWithDbId:chatMsg.dbId status:ChatMsgSendStatusSuccess];
        } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
            [self updateSendStatusWithDbId:chatMsg.dbId status:ChatMsgSendStatusFail];
        }];
        
        [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {

            NSInteger percent = totalBytesWritten * 100.0f / totalBytesExpectedToWrite;
            
            NSDictionary *dict = @{@"msgId":[NSNumber numberWithLongLong:chatMsg.dbId],
                                   @"percent":[NSNumber numberWithInt:percent]};
            [[NSNotificationCenter defaultCenter] postNotificationName:@"UploadChatPicPercent" object:nil userInfo:dict];
        }];
        
        if (resend) {
            [self updateSendStatusWithDbId:chatMsg.dbId status:chatMsg.sendStatus];
        }else {
            [self sendInsertChatMsgNotificationWithMsgArray:[NSArray arrayWithObject:chatMsg]];
        }
    }
}

- (void)sendAckWithMsgArray:(NSArray *)msgArray
{
    PrivateChateMsgNotifyCG_Builder *builder = [PrivateChateMsgNotifyCG builder];
    for (ChatBaseMsg *baseMsg in msgArray) {
        [builder addMsgNum:baseMsg.msgNum];
    }
    
    PrivateChateMsgNotifyCG *notifyCG = [builder build];
    NSData *data = [notifyCG data];
    
    [[IM_Service instance] sendData:data protocolId:Friend_Ack_Send_PID];
}

#pragma mark - 收到消息处理
- (void)handlePacketWithPid:(NSInteger)pid recvData:(NSData *)recvData
{
    if (pid == Friend_SendMsg_Receive_PID) {
        [self handleSendMsgResponseWithRecvData:recvData];
    }else if (pid == Friend_RecMsg_Receive_PID) {
        [self handleReceiveMsgWithRecvData:recvData];
    }
    
}

//私聊消息发送后反馈
- (void)handleSendMsgResponseWithRecvData:(NSData *)recvData
{
    PrivateChatMsgGC *privateChatMsg = [PrivateChatMsgGC parseFromData:recvData];
    
    UInt64 msgNum = privateChatMsg.msgNum;
    UInt32 result = privateChatMsg.privateChatMsgResult;
    
    NSInteger index = [self chatMsgIsSending:msgNum];
    if (index >= 0) {
        [self.msgArray removeObjectAtIndex:index];
    }else {
        return;
    }
    
    ChatMsgSendStatus status ;
    if (result == 1) {
        status = ChatMsgSendStatusSuccess;
    }else if (result == 2) {
        status = ChatMsgSendStatusFail;
    }
    
    [self updateSendStatusWithDbId:msgNum status:status];
}

//收到私聊消息
- (void)handleReceiveMsgWithRecvData:(NSData *)recvData
{
    //少个v,  我勒个去
    PriateChatMsgNotifyGC *privateMsg = [PriateChatMsgNotifyGC parseFromData:recvData];
    
    if (privateMsg.chatMsgList.count > 0) {
        NSMutableArray *receiveArray = [NSMutableArray array];
        NSMutableArray *infoArray = [NSMutableArray array];
        
        PrivateMsgDao *msgDao = [PrivateMsgDao shareInstance];
        
        BOOL result = YES;
        for (ChatMsgBody *msgBody in privateMsg.chatMsgList) {
            PrivateChatMsg *chatMsg = [PrivateChatMsg privateChatMsgWithMsg:msgBody];
                    
            [receiveArray addObject:chatMsg];
            [infoArray addObject:[ChatInfo chatInfoWithPrivateMsg:chatMsg]];
            
            if ([msgDao checkExistWithChatMsg:chatMsg]) {
                result &= [msgDao updateChatMsg:chatMsg];
            }else {
                result &= [msgDao insertPrivateChatMsg:chatMsg];
                result &= [[ChatInfoDao shareInstance] addOrUpdateChatInfo:[ChatInfo chatInfoWithPrivateMsg:chatMsg]];
            }
        }
        if (result) {
            [SoundManager playSound];
            
            //接收消息并且保存成功
            [self sendInsertChatMsgNotificationWithMsgArray:receiveArray];
            
            [self sendAckWithMsgArray:receiveArray];
        }
    }
}

#pragma mark - private
- (void)sendInsertChatMsgNotificationWithMsgArray:(NSArray *)chatMsgArray
{
    NSMutableArray *array = [NSMutableArray array];
    for (PrivateChatMsg *chatMsg in chatMsgArray) {
        UInt64 userId = [CurrentChat shareInstance].chatUser.userId;
        if (chatMsg.sendId == userId || chatMsg.receiveId == userId) {
            [array addObject:chatMsg];
        }
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"AddNewPrivateChatMsg" object:array];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ChatInfoReload" object:nil];
}

- (void)sendUpdateChatMsgSendStatusWithId:(UInt64)dbId status:(ChatMsgSendStatus)status
{
    NSDictionary *dict = @{@"dbId":[NSNumber numberWithLongLong:dbId],
                           @"status":[NSNumber numberWithInteger:status]};
    [[NSNotificationCenter defaultCenter] postNotificationName:@"UpdateChatMsgStatus" object:nil userInfo:dict];
}

- (void)updateSendStatusWithDbId:(UInt64)dbId status:(ChatMsgSendStatus)status
{
    BOOL ret = [[PrivateMsgDao shareInstance] updateSendStatusWithDbId:dbId status:status];
    if (ret) {
        NSLog(@"更新发送状态成功!");
        [self sendUpdateChatMsgSendStatusWithId:dbId status:status];
    }else {
        NSLog(@"更新发送状态失败!");
    }
}

#pragma mark - 超时处理
- (void)handleTimer:(NSTimer *)timer
{
    dispatch_async([IM_Service instance].serviceQueue, ^{
        
        NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
        
        NSMutableArray *removeArray = [NSMutableArray array];
        
        for (PrivateChatMsg *chatMsg in self.msgArray) {
            if ((time - chatMsg.createTime/1000) > 60.0f) {
                chatMsg.sendStatus = ChatMsgSendStatusFail;
                [self updateSendStatusWithDbId:chatMsg.dbId status:ChatMsgSendStatusFail];
                [removeArray addObject:chatMsg];
            }
        }
        [self.msgArray removeObjectsInArray:removeArray];
    });

}

- (void)dealloc
{
    self.timer = nil;
}
@end
